package com.rbac.controller;

import com.rbac.common.Result;
import com.rbac.common.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
@CrossOrigin
public class CaptchaController {
	
	private static final String CAPTCHA_SESSION_KEY = "captcha";
	private static final int CAPTCHA_WIDTH = 120;
	private static final int CAPTCHA_HEIGHT = 40;
	private static final int CAPTCHA_LENGTH = 4;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	/**
	 * 处理CORS预检请求
	 */
	@RequestMapping(value = "/generate", method = RequestMethod.OPTIONS)
	public void handleOptions(HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "*");
		response.setStatus(HttpServletResponse.SC_OK);
	}
	
	/**
	 * 生成验证码图片
	 */
	@GetMapping("/generate")
	public void generateCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
		// 设置CORS头
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "*");
		
		// 创建验证码图片
		BufferedImage image = new BufferedImage(CAPTCHA_WIDTH, CAPTCHA_HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = image.createGraphics();
		
		// 设置背景色
		g2d.setColor(Color.WHITE);
		g2d.fillRect(0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
		
		// 生成随机验证码
		String captchaText = generateRandomCaptcha();
		
		// 设置字体
		g2d.setFont(new Font("Arial", Font.BOLD, 24));
		g2d.setColor(Color.BLACK);
		
		// 绘制验证码文字
		FontMetrics fontMetrics = g2d.getFontMetrics();
		int x = (CAPTCHA_WIDTH - fontMetrics.stringWidth(captchaText)) / 2;
		int y = (CAPTCHA_HEIGHT + fontMetrics.getAscent()) / 2;
		g2d.drawString(captchaText, x, y);
		
		// 添加干扰线
		g2d.setColor(Color.LIGHT_GRAY);
		Random random = new Random();
		for (int i = 0; i < 5; i++) {
			int x1 = random.nextInt(CAPTCHA_WIDTH);
			int y1 = random.nextInt(CAPTCHA_HEIGHT);
			int x2 = random.nextInt(CAPTCHA_WIDTH);
			int y2 = random.nextInt(CAPTCHA_HEIGHT);
			g2d.drawLine(x1, y1, x2, y2);
		}
		
		g2d.dispose();
		
		// 使用Session ID作为captchaId，或可改用前端传入的captchaId
		String captchaId = session.getId();
		String key = RedisKey.CAPTCHA_CODE.build("dev", captchaId);
		stringRedisTemplate.opsForValue().set(key, captchaText, RedisKey.CAPTCHA_CODE.ttl().getSeconds(), TimeUnit.SECONDS);
		
		// 设置响应头
		response.setContentType("image/png");
		response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("X-Captcha-Id", captchaId);
		
		// 输出图片
		ImageIO.write(image, "PNG", response.getOutputStream());
	}
	
	/**
	 * 验证验证码
	 */
	@PostMapping("/verify")
	public Result<Boolean> verifyCaptcha(@RequestBody Map<String, String> request, HttpSession session) {
		String userCaptcha = request.get("captcha");
		String captchaId = request.getOrDefault("captchaId", session.getId());
		String key = RedisKey.CAPTCHA_CODE.build("dev", captchaId);
		String cachedCaptcha = stringRedisTemplate.opsForValue().get(key);
		
		if (cachedCaptcha == null) {
			return Result.error("验证码已过期");
		}
		
		if (userCaptcha == null || userCaptcha.trim().isEmpty()) {
			return Result.error("验证码不能为空");
		}
		
		boolean isValid = cachedCaptcha.equalsIgnoreCase(userCaptcha.trim());
		
		// 验证后清除Redis中的验证码
		stringRedisTemplate.delete(key);
		
		if (isValid) {
			return Result.success(true);
		} else {
			return Result.error("验证码错误");
		}
	}
	
	/**
	 * 生成随机验证码
	 */
	private String generateRandomCaptcha() {
		String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuilder captcha = new StringBuilder();
		Random random = new Random();
		
		for (int i = 0; i < CAPTCHA_LENGTH; i++) {
			captcha.append(chars.charAt(random.nextInt(chars.length())));
		}
		
		return captcha.toString();
	}
} 